import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {Draw, Modify, Snap} from 'ol/interaction';
import { Vector as VectorSource} from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';

import Polygon from "ol/geom/Polygon"  // OpenLayers的多边形几何类，用于表示面状的地理数据
import Feature from 'ol/Feature'  // OpenLayers的要素类，表示地图上的一个对象或实体

class DrawGeometry {
  mapDom:any

  drawSource:any

  type:any = 'Polygon'
  draw:any = null
  snap:any = null

  areaSource:any = new VectorSource()

  constructor (map:any) {
    this.mapDom = map
    this.init()
  }

  init () {
    this.drawSource = new VectorSource();
    const vector = new VectorLayer({
      source: this.drawSource,
      style: new Style({
        fill: new Fill({
          color: 'rgba(255, 255, 255, 0.6)'
        }),
        stroke: new Stroke({
          color: '#0099ff',
          width: 2
        }),
        image: new CircleStyle({
          radius: 7,
          fill: new Fill({
            color: '#0099ff'
          })
        })
      })
    })
    this.mapDom.addLayer(vector)
  }

  drawMethod () {
    if (this.draw) {
      this.mapDom.removeInteraction(this.draw)
    }
    if (this.snap) {
      this.mapDom.removeInteraction(this.snap)
    }

    this.draw = new Draw({
      source: this.drawSource,
      type: this.type
    })
    this.mapDom.addInteraction(this.draw)
    
    this.snap = new Snap({source: this.drawSource})
    this.mapDom.addInteraction(this.snap)

    const modify = new Modify({source: this.drawSource})
    this.mapDom.addInteraction(modify)
  }

  removeDrawMethod () {
    if (this.draw) {
      this.mapDom.removeInteraction(this.draw)
    }
    if (this.snap) {
      this.mapDom.removeInteraction(this.snap)
    }
  }

  drawAllArea (data:any) {
    data.forEach((coordinates:any) => {
      // 创建多边形的几何对象
      let polygon = new Polygon(coordinates)

      // 创建特征（Feature）
      let polygonFeature = new Feature({
        geometry: polygon
      })

      // 设置多边形的样式（Style）
      polygonFeature.setStyle(
        new Style({
          stroke: new Stroke({
            color: 'red', // 多边形边界线的颜色
            width: 2 // 多边形边界线的宽度
          }),
          fill: new Fill({
            color: 'rgba(255, 0, 0, 0.5)' // 多边形填充颜色，这里设置为半透明红色
          })
        })
      )

      this.areaSource.addFeature(polygonFeature)
    })

    // 创建图层并设置源（Layer）
    let layer = new VectorLayer()
    layer.setSource(this.areaSource)

    this.mapDom.addLayer(layer)
  }
}

export default DrawGeometry